//index.js  
var apiHost = wx.getStorageSync('apiHost');

var Appid = wx.getStorageSync('Appid');
var Secret = wx.getStorageSync('Secret');

//获取应用实例  
var app = getApp()
Page({
  data: {
    indicatorDots: false,   //是否显示面板指示点（轮播图）
    autoplay: true,         //是否自动切换（轮播图）
    interval: 6000,         //自动切换时间间隔（轮播图）
    duration: 1000,         //滑动动画时长（轮播图）
    winWidth: 0,
    winHeight: 0,
    collageListLength: '10',//拼团集合长度
    collageListStart: '0',  //拼团集合开始
    // tab切换  
    currentTab: 0,
    imagesLisy: ['https://uhuijia-1254600872.cos.ap-beijing.myqcloud.com/7de55bf9-263a-431b-8264-afe8393287cf.png',             'https://uhuijia-1254600872.cos.ap-beijing.myqcloud.com/087eb775-bd2b-48ec-bebd-108567209977.png','https://uhuijia-1254600872.cos.ap-beijing.myqcloud.com/be4852bc-7594-4e50-989c-eb97ae3c15a0.png'],
    collageList : [],        //拼团集合
    userId :'',             //userId
  },

  /**
   * 页面加载
   */
  onLoad: function () {
    var that = this;
    that.indexHeght();                            //计算高度

    var userId = that.data.userId

    var openId = wx.getStorageSync('openId');     //用户openId获取
    userId = wx.getStorageSync('userId');     //用户userId获取

    var start = that.data.collageListStart;       //起始页
    var length = that.data.collageListLength;     //每页显示多少个
    
    if (userId!=''){
      that.initCollageList(userId, start, length);         //初始化拼团集合
    }

    // 判断openid弹窗授权
    if (openId != '') {
      that.setData({
        openId: openId,
        userId: userId,
        showCancelArea: false
      });
    } else {
      that.setData({
        showCancelArea: true
      });
    }

    /** 
     * 获取系统信息 
     */
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    });
  },

  /**
   * 初始化 拼图列表
   */
  initCollageList: function (userId, start, length){
    var that = this;
    wx.showLoading({
      title: '加载中',
      icon: "loading",
      mask: true
    });

    wx.request({
      url: apiHost + 'hpp/collage/list',
      method: 'GET',
      header: {
        "content-type": 'application/json'
      },
      data: {
        userId: userId,
        start: start,
        length: length
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;
        wx.hideLoading();   //隐藏加载loading
        if ("10000" == code) {
          var collageListData = res.data.data;
          var collageListFlag = that.data.collageList;

          if (collageListFlag.length==0){
            collageListFlag = collageListData
          }else{
            // 追加数据
            for (var i = 0; i < collageListData.length; i++) {
              collageListFlag.push(collageListData[i])
            }
          }

          that.setData({
            collageList: collageListFlag
          });
 
        } else {
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 5000,
            mask: true
          });
        }
      },
      fail: function () {
        wx.hideLoading();   //隐藏加载loading
        wx.showToast({
          title: '网络异常',
          icon: 'none',
          duration: 5000,
          mask: true
        });
      }
    })
  },

  /**
   * 拼团 分页
   */
  collageListScrollLower: function () {
    var that = this;
    var start = that.data.collageListStart;
    var length = that.data.collageListLength;
    var userId = that.data.userId;
    var startFlag = parseInt(start)+1

    that.setData({
      collageListStart: startFlag
    });

    that.initCollageList(userId, startFlag, length);         //初始化拼团集合
  },

  //获取高度
  indexHeght: function () {
    var that = this;
    /*获取指定元素高度*/
    var query3 = wx.createSelectorQuery();
    var indexHeght = "";

    query3.select('#swiper-tab').boundingClientRect()
    query3.exec(function (res) {
      indexHeght = res[0].height;
      wx.getSystemInfo({
        success: function (res) {
          that.setData({
            indexHeght: res.windowHeight - indexHeght
          });
        }
      });
    });
  },

  /** 
     * 滑动切换tab 
     */
  bindChange: function (e) {
    var that = this;
    that.setData({ currentTab: e.detail.current });
  },

  /**
   * 跳转拼团详情
   */
  goCollageDetail : function(e){
    var that = this;
    var collageId = e.currentTarget.dataset.toggle;
    wx.showLoading({
      title: '跳转中',
      icon: 'loading',
      mask: true
    });

    wx.navigateTo({
      url: '../Collage/collageDetail/collageDetail?collageId=' + collageId,
      success: function () {
        wx.hideLoading();   //隐藏加载loading
      },
    });
  },
  /** 
   * 点击tab切换 
   */
  swichNav: function (e) {
    var that = this;
    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    var openId = wx.getStorageSync('openId');     //用户openId获取
    var userId = wx.getStorageSync('userId');     //用户userId获取
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
      var that = this;
      var userId = that.data.userId;

      // 显示顶部刷新图标  
      wx.showNavigationBarLoading(); 

      wx.showLoading({
        title: '加载中',
        icon: "loading",
        mask: true
      });

      wx.request({
        url: apiHost + 'hpp/collage/list',
        method: 'GET',
        header: {
          "content-type": 'application/json'
        },
        data: {
          userId: userId,
          start: '0',
          length: '10'
        },
        success: function (res) {
          var code = res.data.code;
          var msg = res.data.msg;

          if ("10000" == code) {
            var collageListData = res.data.data;
            that.setData({
              collageList: collageListData
            });

          } else {
            wx.showToast({
              title: msg,
              icon: 'none',
              duration: 5000,
              mask: true
            });
          }
          // 隐藏导航栏加载框  
          wx.hideNavigationBarLoading();
          // 停止下拉动作  
          wx.stopPullDownRefresh();
          wx.hideLoading();   //隐藏加载loading
        },
        fail: function () {
          wx.hideLoading();   //隐藏加载loading
          wx.showToast({
            title: '网络异常',
            icon: 'none',
            duration: 5000,
            mask: true
          });
          // 隐藏导航栏加载框  
          wx.hideNavigationBarLoading();
          // 停止下拉动作  
          wx.stopPullDownRefresh();
        }
      })   
  },
  //按钮获取用户信息
  bindGetUserInfo: function (res) {
    var that = this;

    var errMsgFlg = res.detail.errMsg

    if ("getUserInfo:ok" == errMsgFlg) {
      var userCon = res.detail
      wx.login({
        success: function (r) {
          var code = r.code;//登录凭证
          if (code) {
            that.VERBurlUser(userCon, code)
          } else {
            wx.showToast({
              title: '获取用户登录态失败！' + r.errMsg,
              icon: 'none',
              duration: 2000,
              mask: true
            });
          }
        },
        fail: function () {
          wx.hideLoading();   //隐藏加载loading
          wx.showToast({
            title: '登陆失败',
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      })
    }
  },

  /**
  * 解密用户登录完成后的url
  */
  VERBurlUser: function (res, code) {
    var that = this;
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });
    //3.请求自己的服务器，解密用户信息 获取unionId等加密信息  (注意：这个东西必须需要 开放平台 授权)
    wx.request({
      url: apiHost + 'hpp/UserInfo/decodeUserInfo',//自己的服务接口地址
      method: 'post',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        encryptedData: res.encryptedData,
        iv: res.iv,
        code: code,
        Appid: Appid,
        Secret: Secret
      },
      success: function (data) {
        //4.解密成功后 获取自己服务器返回的结果

        if (data.data.status == 1) {
          var userInfo_ = data.data.userInfo;

          var openIdFl = userInfo_.openId;
          var phone = userInfo_.phone;

          that.getuserId(userInfo_.openId);       //获取userId
          wx.setStorageSync('openId', openIdFl);
          wx.setStorageSync('phone', phone);
          wx.setStorageSync('session_token', userInfo_.session_key);
          wx.setStorageSync('userInfo', userInfo_);

          that.setData({
            showCancelArea: false
          });
          that.onLoad();
        } else {
          wx.hideLoading();   //隐藏加载loading
          wx.showToast({
            title: '网络异常',
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
        wx.hideLoading();   //隐藏加载loading
      },
      fail: function () {
        wx.hideLoading();   //隐藏加载loading
        wx.showToast({
          title: '网络异常',
          icon: 'none',
          duration: 2000,
          mask: true
        });
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },
  /**
   * 获取userId
   */
  getuserId: function (openId) {
    var that = this;
    wx.showLoading({
      title: '加载中',
      icon: "loading",
      mask: true
    });

    wx.request({
      url: apiHost + 'hpp/user/userInfoByOpenId',
      method: 'GET',
      header: {
        "content-type": 'application/json'
      },
      data: {
        openId: openId
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;
        var userIdFlag = that.data.userId;
        var start = that.data.collageListStart;       //起始页
        var length = that.data.collageListLength;     //每页显示多少个
        
        wx.hideLoading();   //隐藏加载loading
        if ("10000" == code) {

          if (res.data.data.length!=0){
            var userId = res.data.data.id;
            that.setData({
              userId: userId
            });
            if (userIdFlag == '') {
              that.initCollageList(userId, start, length);         //初始化拼团集合
            }
            wx.setStorageSync("userId", userId)
          }

        } else {
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 5000,
            mask: true
          });
        }
      },
      fail: function () {
        wx.hideLoading();   //隐藏加载loading
        wx.showToast({
          title: '网络异常',
          icon: 'none',
          duration: 5000,
          mask: true
        });
      }
    })
  },
}) 

